<template>
  <!-- 人员管理权限表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '850px' : '850px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
        v-show="!props.isReadonly"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="人员" prop="userName" style="width: 100%">
                <SelectPerson-Member
                  v-if="!props.isReadonly"
                  :maxCollapseTags="10"
                  :showSelectPerson="formData.users"
                  :key="formData.id"
                  :isMultiple="false"
                  @get-person="getPerson"
                  :width="'100%'"
                />
                <span v-else>{{ formData.userName }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="部门"
                prop="departmentName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.departmentName"
                  disabled
                  placeholder="请输入部门"
                  clearable
                />

                <span v-else>{{ formData.departmentName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">资产位置权限</h4>
          <el-button
            type="success"
            plain
            @click="handleAddLocation"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="formData.locationPowerList"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              label="资产位置"
              props="locationName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <!-- <el-form-item
                  :prop="'assetPowerList.' + $index + '.assetTypeName'"
                  :rules="rules.sonassetTypeName"
                  label-width="0"
                >
                  <el-tree-select
                    placeholder="请输入量检具位置"
                    style="width: 100%"
                    filterable
                    v-if="!props.isReadonly"
                    v-model="row.locationId"
                    :data="locationInfoTree"
                    node-key="id"
                    clearable
                    :props="{ label: 'locationName', children: 'nodes' }"
                    check-strictly
                    @node-click="(e) => changeLocation(e, $index)"
                    :render-after-expand="false"
                    @change="(e) => handelLocation(e, $index)"
                  /> -->
                <span>{{ row.locationName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.locationPowerList.length < 2"
                  type="danger"
                  link
                  @click.stop="handleLocationDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">资产类型权限</h4>
          <el-button
            type="success"
            plain
            @click="handleAddAseetType"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="formData.assetPowerList"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <!-- <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            /> -->

            <el-table-column
              label="资产类型"
              props="assetTypeName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <!-- <el-form-item
                  :prop="'assetPowerList.' + $index + '.assetTypeName'"
                  :rules="rules.sonassetTypeName"
                  label-width="0"
                > -->
                <!-- <el-input
                    v-if="!props.isReadonly"
                    v-model="row.assetTypeName"
                    placeholder="请输入资产类型"
                    clearable
                  /> -->
                <!-- <el-tree-select
                    v-if="!props.isReadonly"
                    placeholder="请选择设备种类"
                    v-model="row.assetTypeId"
                    :data="catalogList"
                    node-key="id"
                    :props="{
                      label: 'assetTypeName',
                      value: 'id',
                      children: 'nodes',
                    }"
                    @node-click="(e) => changeAssetType(e, $index)"
                    @change="(e) => hadleAssetType(e, $index)"
                    :render-after-expand="false"
                    :check-strictly="true"
                    style="width: 100%"
                    clearable
                  /> -->
                <span>{{ row.assetTypeName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.assetPowerList.length < 2"
                  type="danger"
                  link
                  @click.stop="handleAseetTypeDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <!-- 详情列表 -->
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        title=""
        :column="2"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">人员</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.userName || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">部门</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.departmentName || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-tabs
        type="border-card"
        v-show="props.isReadonly"
        style="margin-top: 20px"
      >
        <el-tab-pane label="资产位置列表">
          <el-table
            :data="formData.locationPowerList"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />

            <el-table-column
              label="资产位置"
              props="locationName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.locationName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="资产类型列表">
          <el-table
            :data="formData.assetPowerList"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />

            <el-table-column
              label="资产类型"
              props="assetTypeName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.assetTypeName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.assetPowerList.length < 2"
                  type="danger"
                  link
                  @click.stop="handleAseetTypeDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <common-assettype-select
      :visible="selectAssetTypeDialog.visible"
      :LocationList="AssetTypeList"
      @change-visible="changeAssetTypeVisible"
      :assetKind="props.assetKind"
    />
    <common-location-select
      :visible="selectLocationDialog.visible"
      :LocationList="LocationList"
      @change-visible="changeLocationVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMPERSONPOWERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  version: "",
  assetKind: props.assetKind,
  userId: "",
  userEmpNo: "",
  userName: "",
  departmentId: "",
  departmentName: "",
  manageLocation: "",
  manageAssetType: "",
  enabled: 1,
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  users: [],
  assetPowerList: [
    // {
    // id: "",
    // version: "",
    // personPowerId: "",
    // assetTypeId: "",
    // assetTypeCode: "",
    // assetTypeName: "",
    // organizationId: "",
    // createTime: "",
    // createdUserId: "",
    // createdUserName: "",
    // lastUpdateTime: "",
    // lastUpdatedUserId: "",
    // lastUpdatedUserName: "",
    // },
  ],
  locationPowerList: [
    // {
    //   id: "",
    //   version: "",
    //   personPowerId: "",
    //   locationId: "",
    //   locationCode: "",
    //   locationName: "",
    //   organizationId: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  userId: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  userEmpNo: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  userName: [{ required: true, message: "请选择人员", trigger: "change" }],
  departmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  departmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  manageLocation: [
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  manageAssetType: [
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonpersonPowerId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonassetTypeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonassetTypeCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonassetTypeName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleAseetTypeDelete = (index: any) => {
  formData.assetPowerList.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};
const isValidated1 = ref(false);
/** 删除行 */
const handleLocationDelete = (index: any) => {
  formData.locationPowerList.splice(index, 1);
  isValidated1.value && formRef.value.validate(() => {});
};
const assetPowerList = {
  id: "",
  version: "",
  personPowerId: "",
  assetTypeId: "",
  assetTypeCode: "",
  assetTypeName: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};
const locationPowerList = {
  id: "",
  version: "",
  personPowerId: "",
  locationId: "",
  locationCode: "",
  locationName: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};
/** 添加行 */
const handleAddLocation = () => {
  selectLocationDialog.value.visible = true;
  if (formData.locationPowerList.length > 0) {
    getLocationList();
  }
};
/** 添加行 */
const handleAddAseetType = () => {
  selectAssetTypeDialog.value.visible = true;
  console.log(selectAssetTypeDialog.value.visible);

  if (formData.assetPowerList.length > 0) {
    getAssetTypeList();
  }
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        // getdetails();
        formData.users.push({
          id: formData.userId,
          personName: formData.userName,
        });
        console.log(formData.users);
      }
    } else {
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.assetPowerList = [];
  formData.locationPowerList = [];
  formData.id = "";
  formData.version = "";
  formData.assetKind = props.assetKind;
  formData.userId = "";
  formData.userEmpNo = "";
  formData.userName = "";
  formData.departmentId = "";
  formData.departmentName = "";
  formData.manageLocation = "";
  formData.manageAssetType = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.users = [];
}

const loading = ref(false);

/** 人员管理权限保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (
        formData.assetPowerList.length <= 0 ||
        formData.locationPowerList.length <= 0
      ) {
        ElMessage.error("请选择至少一项资产类型及资产位置");
        return;
      }
      str();
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eampersonpower/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

// 以逗号隔开的字符串
const str = () => {
  formData.manageAssetType = formData.assetPowerList
    .map((item: any) => {
      return item.assetTypeName;
    })
    .join(",");
  formData.manageLocation = formData.locationPowerList
    .map((item: any) => {
      return item.locationName;
    })
    .join(",");
};

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eampersonpower/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.assetPowerList = sondetails.data;
}

// 设备种类// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: formData.assetKind },
  }).then((res) => {
    console.log(res.data);

    catalogList.value = res.data;
  });
};

// 点击人员
function getPerson(Ids: string[], Objects: any) {
  if (Objects.length > 0) {
    formData.userId = Objects[0].id;
    formData.userEmpNo = Objects[0].empNo;
    formData.userName = Objects[0].personName;
    formData.departmentId = Objects[0].departmentId;
    formData.departmentName = Objects[0].departmentName;
  } else {
    formData.userId = "";
    formData.userEmpNo = "";
    formData.userName = "";
    formData.departmentId = "";
    formData.departmentName = "";
  }
}

// 资产位置
//资产位置显隐
const selectLocationDialog: any = ref({
  visible: false,
});
const changeLocationVisible = (val: boolean, data: any) => {
  if (data) {
    console.log(data);
    formData.locationPowerList = [];
    data.forEach((item) => {
      formData.locationPowerList.push({
        locationId: item.id,
        locationCode: item.locationCode,
        locationName: item.locationName,
      });
    });
  }
  selectLocationDialog.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const LocationList = ref([]);
const getLocationList = () => {
  LocationList.value = [];
  formData.locationPowerList.forEach((item) => {
    if (item.locationId) {
      LocationList.value.push({
        id: item.locationId,
        locationCode: item.locationCode,
        locationName: item.locationName,
      });
    }
  });
};

// 资产类型
//资产类型显隐
const selectAssetTypeDialog: any = ref({
  visible: false,
});
const changeAssetTypeVisible = (val: boolean, data: any) => {
  if (data) {
    formData.assetPowerList = [];
    data.forEach((item) => {
      formData.assetPowerList.push({
        assetTypeId: item.id,
        assetTypeCode: item.assetTypeCode,
        assetTypeName: item.assetTypeName,
      });
    });
  }
  selectAssetTypeDialog.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const AssetTypeList = ref([]);
const getAssetTypeList = () => {
  AssetTypeList.value = [];
  formData.assetPowerList.forEach((item) => {
    if (item.assetTypeId) {
      AssetTypeList.value.push({
        id: item.assetTypeId,
        assetTypeCode: item.assetTypeCode,
        assetTypeName: item.assetTypeName,
      });
    }
  });
};

onMounted(() => {
  getCAtalogList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
// .formTable {
//   :deep(.el-form-item) {
//     margin: 0 0 13px 0 !important;
//     width: 100%;
//   }
// }

// :deep(.el-dialog .formTable .el-table .el-form-item) {
//   padding: 11px 0 0 0 !important;
// }
// :deep(.el-dialog .formTable .el-table .el-form-item__error) {
//   font-size: 11px !important;
// }

// :deep(.el-dialog .formTable .el-table) {
//   // .cell.el-tooltip {
//   //   padding: 0 15px;
//   // }

//   // .el-table__body td.el-table__cell {
//   //   padding: 20;
//   // }
//   // .cell.el-tooltip {
//   //   padding: 5px;
//   // }
//   .el-table__body td.el-table__cell {
//     // padding: 5px !important;
//     padding: 0 !important;
//   }
// }

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
